package com.shu.shiro.controller;

import com.shu.shiro.common.CodeMsg;
import com.shu.shiro.common.Result;
import com.shu.shiro.model.User;
import com.shu.shiro.vo.LoginVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {
    @RequestMapping("/login")
    public String login(){
        return "login";
    }
    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("rusult",Result.success("登录 成功"));
        return "index";
    }

    /**
     * 登录
     * @param loginVo
     * @param model
     * @return
     */
    @RequestMapping("/loginUser")
    @ResponseBody
    public Result loginUser(LoginVo loginVo, Model model){
        UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword(),loginVo.isRememberMe());
        Subject subject = SecurityUtils.getSubject();

        subject.login(token);
        User user=(User) subject.getPrincipal();
        model.addAttribute("user",user);
        return Result.success(user);
    }
    @RequestMapping("/admin")
    @ResponseBody
    public Result admin(){
        return Result.success("admin success");
    }
    @RequestMapping("/edit")
    @ResponseBody
    public String edit(){
        return "edit success";
    }
    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject!=null){
            subject.logout();
        }
        return "login";
    }
    @RequestMapping("/unauthorized")
    public String unauthorized(){

        return "unauthorized";
    }
    @RequiresRoles("admin")
    @RequestMapping("/zhujie")
    @ResponseBody
    public Result zhujie(){

        return Result.success("注解权限成功");
    }
    //被踢出后跳转的页面
    @RequestMapping(value = "/kickout", method = RequestMethod.GET)
    public String kickOut() {
        return "kickout";
    }

}
